
// 1. 创建router对象
var express = require('express')
var router = express.Router()
const furModel = require('../database/models/furModel');

// 2. 在router下挂载接口
// 批量转存接口

router.post('/',async (req,res)=>{
  // 1. 接收客户端提交的post数据
  let arr = req.body.list
  let result = await furModel.insertMany(arr)
  res.send({
    code:1,
    msg:'批量录入成功'
  })
})

// 删除家具数据
router.delete('/',async (req,res)=>{
  let {id} = req.query
  try {
    await furModel.deleteOne({_id:id})
    res.send({code:1,msg:'删除成功'})
  } catch (error) {
    res.send({code:0,msg:'删除失败'})
  }
  console.log('123');
})


//更新家具
router.put('/',async (req,res)=>{
  let {id} = req.query
  try {
    await furModel.updateOne({_id:id},req.body)
    res.send({code:1,msg:'更新成功'})
  } catch (error) {
    res.send({code:1,msg:'更新失败'})
  }
})

//查询、分页
router.get('/',async (req,res)=>{
  let {pageSize=10,page=1} = req.query  //设置参数默认值
  let skipNum = (page-1)*pageSize
  let result = await furModel.find().limit(pageSize).skip(skipNum)
  res.send({
    code:1,
    msg:'家具列表查询成功',
    data:result
  })
})

//搜索
router.get('/search',async (req,res)=>{
  let {keyword} = req.query  //设置参数默认值
  // let result = await furModel.find({name:keyword}) //精准匹配
  let regExp = new RegExp(keyword,'i') //正则对象
  let result = await furModel.find({name:regExp}) //正则匹配、模糊查询
  res.send({
    code:1,
    msg:'搜索成功',
    data:result
  })
})

// 3. 抛出router
module.exports = router